import router from '@/router/index'
import store from '@/store/index'
import NProgress from "nprogress"
import "nprogress/nprogress.css"

NProgress.configure({ showSpinner: false })

const WHITE_LIST = ['/login']

router.beforeEach((to, from, next) => {
  NProgress.start()
  //顶部nav相关操作
  headerHandler(to)
  authHandler(to, next)
})

/**
 * header 显示/隐藏
 * @param {Object} route 路由元信息
 */
function headerHandler(route) {
  let isLoginPage = true
  if (route.name === 'Login') {
    isLoginPage = true
  } else {
    isLoginPage = false
  }
  store.dispatch('app/setIsLoginPage', isLoginPage)
}

/**
 *
 * @param {*} route router.beforeEach((to,from,next)) 中的to对象
 * @param {*} next router.beforeEach((to,from,next)) 中的next对象
 */

async function authHandler(route, next) {
  if (store.getters.token) {  //有token
    if (route.name === 'Login') {
      next()
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.roles.length > 0 ? true : false
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          await store.dispatch('app/setUserInfo')
          next()
        } catch (error) {
          await store.dispatch('app/resetToken')
          next(`/login?redirect=${route.path}`)
          NProgress.done()
        }
      }
    }
  } else { //无token
    if (WHITE_LIST.indexOf(route.path) !== -1) {  //白名单直接进入
      next()
    } else {  //其它直接重定向到登陆
      next({ path: `/login?redirect=${route.path}` })
      NProgress.done()
    }
  }
}

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
/**
 *
 * @param {Array<string>} roles 权限列表
 * @param {String} role 路由权限
 */
function hasPermission(roles, role) {
  return roles.includes(role)
}
